package com.gfl.trivialrestclient.controllers;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gfl.trivialrestclient.model.Product;
import com.gfl.trivialrestclient.model.Role;
import com.gfl.trivialrestclient.model.User;
import com.gfl.trivialrestclient.services.ProductService;
import com.gfl.trivialrestclient.services.UserService;

/**
 * Make initial configuration and population of data
 * 
 * @author student
 * 
 */
public class BootstrupContextListinner implements ServletContextListener {
	private final Log log = LogFactory.getLog(getClass());
	private ProductService productService;
	private UserService userService;

	@Override
	public void contextInitialized(ServletContextEvent event) {
		WebApplicationContext wac = WebApplicationContextUtils
				.getWebApplicationContext(event.getServletContext());
		if (wac == null) {
			log.error("Can't extract  WebApplicationContext");
			return;
		}
		productService = wac.getBean(ProductService.class);
		userService = wac.getBean(UserService.class);

		populateDbWithTestPoductData();
		populateDbWithTestUserData();
	}

	private void populateDbWithTestPoductData() {
		if (productService == null) {
			log.error("Can't create stub product data. ProductService not autowired");
			return;
		}

		try {
			productService.create(new Product.Builder().name("prod1").units(1)
					.weight(100.0).addedNow().build());
			productService.create(new Product.Builder().name("prod2").units(2)
					.weight(200.0).addedNow().build());
			productService.create(new Product.Builder().name("prod3").units(3)
					.weight(300.0).addedNow().build());
			log.info("OK populated DB with products");
		} catch (DataAccessException dataAccessException) {
			log.error("Can't create stub product data", dataAccessException);
		}
	}

	private void populateDbWithTestUserData() {
		if (userService == null) {
			log.error("Can't create stub data. UserDao not autowired");
			return;
		}

		try {
			Role adminRole = userService.createRole("ROLE_ADMIN");

			User user = new User("user", "user", "user@gmail.com");
			userService.createUser(user);

			User admin = new User("admin", "admin", "admin@gmail.com");
			userService.createUser(admin);
			userService.addRoleToUser(admin, adminRole);

			log.info("OK populated DB with users");
		} catch (DataAccessException dataAccessException) {
			log.error("Can't create stub user data", dataAccessException);
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		productService = null;
		userService = null;
	}

}
